import {
  createPromoterQrCode,
  getAdvertisingList,
  GetAdvertisingListReq,
} from "@/services";
import { useUserStore } from "@/store";
import { useSafeState, useUpdate } from "ahooks";
import React, { FC, useEffect, useRef } from "react";
import { Button, Toast } from "antd-mobile";
import { history } from "umi";
import { parseImageUrl } from "@/utils";
const InviteQrcode: FC = () => {
  const { userInfo } = useUserStore();
  const [qrcodeBase64, setQrcodeBase64] = useSafeState("");
  const posterBaseUrlRef = useRef("");
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const qrcodeBase64Ref = useRef("");
  const showImageRef = useRef("");
  const update = useUpdate();

  async function urlToBase64(url: string): Promise<string> {
    try {
      const response = await fetch(url);
      if (!response.ok) {
        throw new Error("Network response was not ok " + response.statusText);
      }
      const blob = await response.blob();
      const reader = new FileReader();
      reader.readAsDataURL(blob);
      return new Promise((resolve, reject) => {
        reader.onloadend = () => resolve(reader.result as string);
        reader.onerror = reject;
      });
    } catch (error) {
      console.error("Error fetching or reading the image:", error);
      throw error;
    }
  }

  const getDataRequest = async (params?: Partial<GetAdvertisingListReq>) => {
    const req: GetAdvertisingListReq = {
      type: 4,
    };
    const res = await getAdvertisingList(req);
    if (res.code == 200) {
      const posterLi = res.data.list.filter((item) => item.title == "销售海报");
      const url = posterLi[0].imgUrl;
      const imageUrl = parseImageUrl(url);
      posterBaseUrlRef.current = await urlToBase64(imageUrl);
    }
  };

  const genQrcode = async () => {
    Toast.show({
      icon: "loading",
      duration: 0,
      content: "加载中…",
    });
    const res = await createPromoterQrCode({
      appId: process.env.UMI_APP_WECHAT_ID || "",
      AppType: 1,
      userId: userInfo.onlyId, // 用户id
      type: 1, // 0-前端；1-后台
    }).catch((err) => {
      Toast.clear();
      Toast.show({
        icon: "fail",
        content: "生成二维码失败！",
      });
      history.back();
    });
    Toast.clear();
    if (res && res.code == 200) {
      const qrcode = "data:image/png;base64," + res.data.qrCode;
      setQrcodeBase64(qrcode);
      qrcodeBase64Ref.current = qrcode;
    }
  };

  useEffect(() => {
    genQrcode();
    getDataRequest();
  }, []);

  useEffect(() => {
    let bgImage = new Image();
    let qrcodeImage = new Image();
    let isMounted = true;
    let imagesLoaded = 0;
    function imageLoadHandler() {
      imagesLoaded++;
      if (imagesLoaded === 2 && isMounted) {
        drawImages();
      }
    }
    bgImage.onload = imageLoadHandler;
    qrcodeImage.onload = imageLoadHandler;

    bgImage.src = posterBaseUrlRef.current;
    qrcodeImage.src = qrcodeBase64Ref.current;

    return () => {
      isMounted = false;
      bgImage.onload = null;
      qrcodeImage.onload = null;
    };

    function drawImages() {
      const canvas = canvasRef.current as HTMLCanvasElement;
      const ctx = canvas.getContext("2d");
      const num = 2;
      ctx?.drawImage(bgImage, 0, 0, 360 * num, 780 * num);
      ctx?.drawImage(qrcodeImage, 134 * num, 614 * num, 90 * num, 90 * num);
      showImageRef.current = canvasRef.current?.toDataURL("image/png") || "";
      update();
    }
  }, [posterBaseUrlRef.current, qrcodeBase64Ref.current]);

  const generateImage = () => {
    // const link = document.createElement("a");
    // link.href = showImageRef.current;
    // link.download = "sale-image.png"; // 设置下载文件名
    // // 模拟点击
    // link.click();
    // // 清除引用以释放资源
    // link.remove();
  };

  return (
    <div>
      <div className="mt-20px center">
        {showImageRef.current ? (
          <>
            <img className="w-360px h-780px" src={showImageRef.current}></img>
          </>
        ) : (
          <canvas
            className="w-360px h-780px overflow-hidden"
            ref={canvasRef}
            width={360 * 2}
            height={780 * 2}
          />
        )}
      </div>
      <div className="mt--60px center">
        {showImageRef.current && (
          <Button
            className="w-300px"
            color="primary"
            fill="solid"
            onClick={() => {
              generateImage();
            }}
          >
            长按图片保存
          </Button>
        )}
      </div>
    </div>
  );
};

export default InviteQrcode;
